/*
WIDGET FOR EXTENDING BLACKBOARD CAPABILITY, UNIVERSITY OF READING
DEEP LINK JS

MIT/X11 LICENSE
Copyright (C) 2012 Guy Pursey (@ University of Reading)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/

var BBRDGWS = BBRDGWS || {};

BBRDGWS.versioning = BBRDGWS.versioning || {};
BBRDGWS.versioning.loadVideoUploadForm = BBRDGWS.versioning.loadVideoUploadForm || {
		version: '',
		date: '20121214',
		time: '1545',
		description: 'When called, this method creates some buttons with which users can retrieve a deep link to a particular item within Blackboard.'
	};

BBRDGWS.loadDeepLink = BBRDGWS.loadDeepLink || function (courseObject) {
	"use strict";

	var redirectURL = 'https://www.bb.reading.ac.uk/bbcswebdav/xid-2732267_1',
		/* PLACE THE PERMANENT URL OF bbrdg_redirectpage.html BETWEEN THE SINGLE QUOTATION MARKS */
		// https://www.bb.reading.ac.uk/bbcswebdav/xid-2732267_1
		// http://vibb10.reading.ac.uk/bbcswebdav/xid-3626_1
		
		redirectAnchor = '?', // in anticipation of redirecting to a specific course item
		tValue = '_2_1', // default tab set to 'Enrolments'
		searchString = top.location.search.substring(1),
		nvPairs = searchString.split("&"),
		nvPair, // for individual paired elements in the nvPairs array
		i = nvPairs.length, // reverse counter
		b = 0, // counter
		menuArea,
		linkButton,
		subjectLine,
		bodyText,
		emailSubject,
		emailBody,
		emailButton,
		helpButton,
		linkDisplay,
		linkTextBox,
		helpDisplay,
		idAppend,
		widgetBoxes,
		widgetMessages,
		courseString = (courseObject) ? (courseObject.courseId || '') : '', // fetches the id of the relevant course from the object in the argument
		contentString = (courseObject) ? (courseObject.contentId || '') : '', // fetches the id of the relevant content item from the object in the argument
		pageTitleText = (courseObject) ? (courseObject.contentTitle || '') : '', // fetches the title of the relevant content item from the object in the argument
		nominatedPlaceHolder = document.getElementById(contentString) || (document.getElementById('navsecondary') || document.getElementById('pageTitleDiv')), // nominates an element on the page to which the buttons can be attached
		documentStatus = (document.body) ? (document.body.contentEditable || '') : '', // indicates whether the document is being edited or not ('true' if it is; 'inherited' if it isn't)
		courseItem = document.getElementById('contentListItem:' + contentString),
		rtn = true; // in case there ever needs to be a check, to ascertain the method has run properly

	while (i) {
		// this is really more initialisation stuff and shouldn't have to happen more than once... need a cache property of some kind?
		i -= 1;
		nvPair = nvPairs[i].split("=");
		if (nvPair[0] === "tab_tab_group_id") {
			tValue = nvPair[1];
		}
	}

	if (documentStatus === 'true') {
		/* the page is currently being edited; do not display the buttons but a message about the widget instead */
		
		widgetMessages = BBRDGWS.getElementsByClassName('', 'widgetMsg', '', function (obj) {
			//obj.style.border = '1px solid #000000';
			//obj.style.width = '400px';
			//obj.padding = '5px';
			//obj.display = 'block';
			obj.innerHTML = 'This box contains the Deep Link widget. ' +
				'When you are not editing this item, it will create buttons that provide a direct link to your course item. ' +
				'Please do not remove unless you believe the widget is causing you problems or unless you no longer want to use these buttons. ' +
				'Contact elearning-support@reading.ac.uk if you require advice.';
		});
		
		widgetBoxes = BBRDGWS.getElementsByClassName('', 'cdmWidget', '', function(obj) {
			obj.display = 'block';
		});
		
	} else if (documentStatus === 'inherit') {
		/* the page is not currently being edited */
		/* centralised library of condition checkers would be good, for maintainability */
		
		widgetBoxes = BBRDGWS.getElementsByClassName('', 'cdmWidget', '', function(obj) {
			obj.display = 'block';
		});
		
		/* in case the message comes loose of the container */
		widgetMessages = BBRDGWS.getElementsByClassName('', 'widgetMsg', '', function(obj) {
			obj.display = 'none';
			obj.innerHTML = '';
		});

		if (tValue !== null && tValue.length > 3) {
			redirectAnchor += tValue.substring(tValue.indexOf("_") + 1, tValue.lastIndexOf("_1"));
		}

		if (location.pathname.substr(location.pathname.lastIndexOf('/') + 1) === 'displayLearningUnit') {
			nominatedPlaceHolder = document.getElementById('navsecondary');
		}

		courseString = courseString.substring(courseString.indexOf("_") + 1, courseString.lastIndexOf("_1"));
		contentString = contentString.substring(contentString.indexOf("_") + 1, contentString.lastIndexOf("_1"));
		// it's not pretty but this gives us the main part of the string that we need...
		// no spaces, no underscores and no apparently unnecessary suffices (like "_1")
		idAppend = courseString + contentString;

		redirectAnchor += "&" + courseString;
		redirectAnchor += "&" + contentString;
		redirectAnchor += "&1";
		redirectURL += redirectAnchor;

		pageTitleText = pageTitleText.replace(/(\r\n|\n|\r)/gm, " "); // replace all line breaks with a space
		pageTitleText = pageTitleText.replace(/\s+/g, " "); // replace all double spaces with a single space
		if (pageTitleText.substr(0, 1) === " ") {
			pageTitleText = pageTitleText.substring(1); // if first character is a space strip it out
		}

		/* NOTE TO SELF: May be better if all the below is done with innerHTML; assuming it doesn't cause problems for IE it could be much quicker. */

		nominatedPlaceHolder.style.position = 'relative';

		if (!document.getElementById('menuArea' + idAppend)) {
			menuArea = document.createElement('li');
			menuArea.id = 'menuArea' + idAppend;
			menuArea.className = "secondaryButton";
			menuArea.style.position = 'relative';
			menuArea.style.right = '0';
			menuArea.style.display = 'inline-block';
			nominatedPlaceHolder.appendChild(menuArea);
		}

		linkButton = document.createElement('a');
		linkButton.className = 'button-3-img tocNavLink';
		linkButton.target = '_blank';
		linkButton.innerHTML = '<span id="linkButtonText' + idAppend + '" style="display: inline; line-height: 100%; background-image: none;" class="tocNavText">Show Link</span>&nbsp;&nbsp;<img alt="(Click to see options)" src="/images/ci/ng/expand.gif">';
		// 
		linkButton.style.cursor = 'pointer';
		linkButton.onclick = function () {
			if (document.getElementById('linkDisplay' + idAppend).style.display === 'none') { // check element exists?
				document.getElementById('linkDisplay' + idAppend).style.display = 'block';
				document.getElementById('linkButtonText' + idAppend).firstChild.nodeValue = 'Hide Link'; // for some reason this does not work in IE
				linkTextBox.select();
			} else {
				document.getElementById('linkDisplay' + idAppend).style.display = 'none';
				document.getElementById('linkButtonText' + idAppend).firstChild.nodeValue = 'Show Link'; // for some reason this does not work in IE
			}
		};
		document.getElementById('menuArea' + idAppend).appendChild(linkButton);

		subjectLine = "Link to an item in Blackboard: " + pageTitleText;
		bodyText = ["Hello,", "", "This deep link will take you to an item in Blackboard called '" + pageTitleText + "':", redirectURL];

		emailSubject = encodeURIComponent(subjectLine);
		emailBody = "";
		for (b = 0; b < bodyText.length; b += 1) {
			emailBody += encodeURIComponent(bodyText[b]) + "%0D%0A";
		}

		emailButton = document.createElement('a');
		emailButton.className = 'button-3-img tocNavLink';
		emailButton.href = "mailto:?subject=" + emailSubject + "&body=" + emailBody;
		emailButton.target = "_self";
		emailButton.innerHTML = "Email Link";
		document.getElementById('menuArea' + idAppend).appendChild(emailButton);

		helpButton = document.createElement('a');
		helpButton.className = 'button-3-img tocNavLink';
		helpButton.target = '_blank';
		helpButton.innerHTML = '<span id="helpButtonText' + idAppend + '" style="display: inline; line-height: 100%; background-image: none;">?</span>';
		helpButton.style.cursor = 'pointer';
		helpButton.onclick = function () {
			if (document.getElementById('helpDisplay' + idAppend).style.display === 'none') {
				document.getElementById('helpDisplay' + idAppend).style.display = 'block';
				document.getElementById('helpButtonText' + idAppend).firstChild.nodeValue = 'x';
			} else {
				document.getElementById('helpDisplay' + idAppend).style.display = 'none';
				document.getElementById('helpButtonText' + idAppend).firstChild.nodeValue = '?';
			}
		};
		document.getElementById('menuArea' + idAppend).appendChild(helpButton);

		linkDisplay = document.createElement('a');
		linkDisplay.id = 'linkDisplay' + idAppend;
		linkDisplay.className = 'button-3-img tocNavLink';
		linkDisplay.style.display = 'none';
		linkDisplay.style.zIndex = '100';
		linkDisplay.style.position = 'absolute';
		linkDisplay.style.cursor = 'text';
		linkDisplay.style.width = '100%';
		linkDisplay.onmouseover = function () { };
		linkDisplay.onfocus = function () { };
		//linkDisplay.style.cssFloat = 'right';
		linkDisplay.style.right = '0px';
		linkDisplay.style.top = '30px';
		linkDisplay.style.whiteSpace = 'nowrap';
		//linkDisplay.innerHTML = redirectURL;
		document.getElementById('menuArea' + idAppend).appendChild(linkDisplay);
		
		linkTextBox = document.createElement('input');
		linkTextBox.type = 'text';
		linkTextBox.style.border = '0px none #000';
		linkTextBox.style.width = '100%';
		linkTextBox.value = redirectURL;
		linkTextBox.readOnly = true;
		document.getElementById('linkDisplay' + idAppend).appendChild(linkTextBox);

		helpDisplay = document.createElement('a');
		helpDisplay.id = 'helpDisplay' + idAppend;
		helpDisplay.className = 'button-3-img tocNavLink';
		helpDisplay.style.display = 'none';
		helpDisplay.style.zIndex = '100';
		helpDisplay.style.position = 'absolute';
		//helpDisplay.style.whiteSpace = 'nowrap'; // for IE only, where div is hidden behind other buttons.
		helpDisplay.style.right = '0px';
		helpDisplay.style.top = '30px';
		helpDisplay.innerHTML =	'These buttons can help people find this item. Copy the link under <i>Show Link</i> to paste into a message, ' +
			'or use <i>Email Link</i> to send it directly with your mail client (e.g., Microsoft Outlook).';
		document.getElementById('menuArea' + idAppend).appendChild(helpDisplay);

	} //eof

	return rtn;
};

BBRDGWS.getElementsByClassName = BBRDGWS.getElementsByClassName || function (parentElement, class_name, tag, callback) {
	"use strict";
	/*jslint browser: true */
	/*global top: true */
	/* Code originally taken from http://lawrence.ecorp.net/inet/samples/js-getelementsbyclassnameex.shtml and refactored by Guy */

	var matchArray = [],
		re = new RegExp("(?:^|\\s)" + class_name + "(?:\\s|$)"),
		docList,
		len;

	tag = tag || "*";
	callback = callback || function (obj) { };
	parentElement = parentElement || document;
	if (typeof parentElement === "string") {
		/* object could be passed instead of Id */
		parentElement = document.getElementById(parentElement);
	}

	/* Get array of tags */ /* could potentially refactor this to one clear line at top of function, with ternary operator, default operator and some parens */
	if (tag === "*") {
	   /* This test is to accommodate IE5 */
		docList = parentElement.all || parentElement.getElementsByTagName(tag);
	} else {
		docList = parentElement.getElementsByTagName(tag);
	}

	/* Create output array */ /* if the above is refactored, we could move this assignment into the declaration at the top too */
	len = docList.length;

	while (len) { /* slightly refactored while-loop to pass JSLint */
		len -= 1;
		if (re.test(docList[len].className)) {
			matchArray[matchArray.length] = docList[len];
			callback(matchArray[matchArray.length - 1]);
		}
	}
	return matchArray.reverse();
}; //eof